"use strict";

var router = require("router"),
    TokenService = require("router").TokenService,
    mongo = require('./core/mongoservice'),
    ObjectId = require('mongodb').ObjectID,
    Q = require('q');

function GridFSService() {
    console.log("GridFSService constructor");
    this.uploadedImage = null;
    this.re = /data:(\S*);(\S*),(.+)/;
}
GridFSService.prototype = Object.create(TokenService.prototype);
GridFSService.prototype.constructor = GridFSService;


GridFSService.prototype.get = function (objectId) {
    return Q.fcall(function () {
        objectId = new ObjectId(objectId);
        return mongo.gridStore(objectId, "r").then(function (gs) {
            return Q.ninvoke(gs, 'open').then(function (gs) {
                return Q.ninvoke(gs, 'read').then(function (data) {
                    return Q.ninvoke(gs, 'close').then(function () {
                        return {
                            image: data,
                            contentType: gs.contentType
                        };
                    });
                });
            });
        });
    });
};

GridFSService.prototype.save = function (contentType, buffer) {
    var self = this;
    var objectId = new ObjectId();
    return mongo.gridStore(objectId, "w", { "content_type": contentType, j: true }).then(function (gs) {
        return Q.ninvoke(gs, 'open').then(function (gs) {
            return Q.ninvoke(gs, 'write', buffer).then(function (gs) {
                return Q.ninvoke(gs, 'close').then(function () {
                    return { id: objectId};
                });
            });
        });
    });
};

exports = module.exports = new GridFSService();